package com.ztzh.temteam.websocket;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ztzh.temteam.controller.TenTeamController;
import com.ztzh.temteam.example.Main;
import com.ztzh.temteam.example.dto.chat.ChatMessage;
import com.ztzh.temteam.example.dto.chat.ChatRequest;
import com.ztzh.temteam.utils.ApiAuthUtil;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.java_websocket.server.WebSocketServer;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.WebSocket;
import org.java_websocket.framing.Framedata;
import org.java_websocket.framing.CloseFrame;

import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Component;

@Component
public class CustomWebSocketServer extends WebSocketServer {

    private Set<WebSocket> connections = Collections.newSetFromMap(new ConcurrentHashMap<>());

    public CustomWebSocketServer() {
        super(new InetSocketAddress("localhost", 8485)); // 选择端口号
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        connections.add(conn);
        System.out.println("New connection: " + conn.getRemoteSocketAddress());
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        connections.remove(conn);
        System.out.println("Closed connection: " + conn.getRemoteSocketAddress() + " - Reason: " + reason);
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println("Received message from " + conn.getRemoteSocketAddress() + ": " + message);
      //  conn.send("Echo: " + message);
        // Invoke chat method and get response
        StringBuffer buffer = new StringBuffer();
        try {
            chat(Main.chatUrl, TenTeamController.getFileId().getFirst(), message, Main.appId, Main.secret, conn, buffer);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        ex.printStackTrace();
        if (conn != null) {
            connections.remove(conn);
            System.out.println("Error: " + conn.getRemoteSocketAddress());
        }
    }



    @Override
    public void onStart() {
        System.out.println("WebSocket server started successfully");
        setConnectionLostTimeout(0);
        setConnectionLostTimeout(100);
    }
    /**
     * 聊天
     * @param chatUrl
     * @param fileId
     * @param question
     * @param appId
     * @param secret
     */
    public void chat(String chatUrl, String fileId, String question, String appId, String secret,WebSocket serverConn, StringBuffer buffer) throws URISyntaxException {
        ChatMessage message = new ChatMessage();
        message.setRole("user");
        message.setContent(question);
        // 请求内容
        ChatRequest request = ChatRequest.builder()
                .fileIds(Collections.singletonList(fileId))
                .topN(3)
                .messages(Collections.singletonList(message))
                .build();

        // 构造url鉴权
        long ts = System.currentTimeMillis() / 1000;
        String signature = ApiAuthUtil.getSignature(appId, secret, ts);
        String requestUrl = chatUrl + "?" + "appId=" + appId + "&timestamp=" + ts + "&signature=" + signature;


        WebSocketClient webSocketClient = new WebSocketClient(new URI(requestUrl)) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                // 连接成功后发送请求
                send(JSONUtil.toJsonStr(request));
            }

            @Override
            public void onMessage(String message) {
                JSONObject jsonObject = JSONUtil.parseObj(message);
                String content = jsonObject.getStr("content");
                if (StrUtil.isNotEmpty(content)) {
                    buffer.append(content);
                }
                if (Objects.equals(jsonObject.getInt("status"), 2)) {
                    serverConn.send(buffer.toString());
                    close();
                }
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                System.out.println("WebSocket 连接关闭: " + reason);
            }

            @Override
            public void onError(Exception ex) {
                ex.printStackTrace();
            }
        };

        webSocketClient.connect();
    }



}